/* Copyright(C): Leaf Johnson 2009,2010

    This file is part of leaf-lib.

    leaf-lib is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    leaf-lib is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with leaf-lib.  If not, see <http://www.gnu.org/licenses/>.


 * 
 * 
 */


#ifndef MTI_H_INCLUDED
#define MTI_H_INCLUDED

/*+ 移植相关，需要一个特定的读/写函数，可以指定特定的端口号，linux下就可以把MtiPort定义成fd的类型 */
#include <devices/uart.h>
typedef uint8_t MtiPort;
static inline int mti_write( MtiPort p, const void *buf, size_t sz )
{
	return uart_write( p, buf, sz );
}
static inline int mti_read( MtiPort p, void *buf, size_t sz )
{
	return uart_read( p, buf, sz );
}
/*- 移植相关，需要一个特定的读/写函数，可以指定特定的端口号，linux下就可以把MtiPort定义成fd的类型 */

/* mti驱动的错误号 */
#define MTI_ERR_TO   -1
#define MTI_ERR_COMM -2
#define MTI_ERR_SBUF -3
#define MTI_ERR_MSG -4
#define MTI_ERR_VALUE 255

/* 设备的一些特性 */
#define MTI_SINGLE ((uint8_t)(0xFF))
#include "mtimid.h"

typedef struct{
	size_t capacity;
	uint8_t body[3];
}MtiMsg;

#define DEF_MTI_MSG_EX( name, sz, adj ) \
	adj uint8_t name##Mem[ sizeof(MtiMsg) + (sz) ]; \
	static const size_t name##Mem##Sz = (sz); \
	adj MtiMsg *name = (MtiMsg *)name##Mem

#define DEF_MTI_MSG( name, sz ) \
	DEF_MTI_MSG_EX( name, sz, static )

#define MTIM_INIT( name ) \
	name->capacity = name##Mem##Sz
/* 发消息，自动添加校验位 */
int mti_send( MtiPort port, const MtiMsg *msg );
/* 收消息，返回正数表示消息id, 返回负数表示出错，错误号在上面有定义 */
int mti_recv( MtiPort port, MtiMsg *msg );
MtiMsg *mti_create_msg( void *mem, size_t sz );

/* 消息设置与获取设置 */
uint8_t mtim_get_id( const MtiMsg *msg );
uint8_t mtim_get_mid( const MtiMsg *msg );
size_t mtim_get_size( const MtiMsg *msg );
size_t mtim_get_bodysize( const MtiMsg *msg );
void mtim_set_id( MtiMsg *msg, uint8_t id );
void mtim_set_mid( MtiMsg *msg, uint8_t id );
void mtim_set_size( MtiMsg *msg, size_t sz );
void mtim_set_data( MtiMsg *msg, size_t idx, uint8_t data );
void mtim_make( MtiMsg *msg, uint8_t mid, size_t sz, ... );
int  mti_adjust_angle( int angle );

/* 数据获取，我只支持获取F1220格式的整数部分，下标表示第几个数据 */
int mtim_get_int( MtiMsg *msg, size_t idx );

#endif
